#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from Utils.Logger import logger
from Utils.Timer import timer
from Utils.LoadConfig import load_script_excels_config
from Src.ScriptExcelParser import ScriptExcelParser
from Config.PackPath import SCRIPT_EXCEL_DIR, CONFIG_EXCEL_DIR
from collections import defaultdict
import os
import re


class TimeLimitItems(ScriptExcelParser):
    """解析 时效道具.xlsx"""
    def parse_items(self):
        """
        解析道具，获取道具信息
        :return: 四元组列表，包括道具类型，道具类型编号，道具名称，道具时效
        """
        ws = self.get_worksheet('Data')
        re_pattern = '^([\s\S]*)[-]([\s\S]*)[(]([\d])([\s\S]*)[)]$'
        result_list = list()
        for row in range(2, ws.max_row + 1):
            item_info = ws.cell(row, 1).value
            if item_info is not None:
                script_config = load_script_excels_config()
                info = re.match(re_pattern, item_info)
                item_type = info.group(1)
                item_type_id = str(script_config['皮肤类型'][item_type]['皮肤类型编号'])
                item_name = info.group(2)
                item_time_limit = info.group(3)
                result = (item_type, item_type_id, item_name, item_time_limit)
                result_list.append(result)
            else:
                break
        return result_list

    def parse_shopconfig_title(self):
        ws = self.get_worksheet('ShopConfig')
        title_list = list()
        for col in range(1, ws.max_column + 1):
            title = ws.cell(1, col).value
            if title:
                title_list.append(title)
            else:
                break
        return title_list

    def parse_objects_title(self):
        ws = self.get_worksheet('objects')
        title_list = list()
        for col in range(1, ws.max_column + 1):
            title = ws.cell(1, col).value
            if title:
                title_list.append(title)
            else:
                break
        return title_list

    def write_item_id(self, id_list):
        ws = self.get_worksheet('Data')
        row = 2
        for id_ in id_list:
            ws.cell(row, 2).value = id_
            row += 1

    def write_shopconfig(self, shopconfig_list):
        ws = self.get_worksheet('ShopConfig')
        title_list = self.parse_shopconfig_title()
        row = 2
        for shopconfig_dict in shopconfig_list:
            for key, val in shopconfig_dict.items():
                idx = title_list.index(key)
                if val is not None:
                    val = str(val)
                ws.cell(row, idx + 1).value = val
            row += 1

    def write_objects(self, objects_list):
        ws = self.get_worksheet('objects')
        title_list = self.parse_objects_title()
        row = 2
        for objects_dict in objects_list:
            for key, val in objects_dict.items():
                idx = title_list.index(key)
                if val is not None:
                    val = str(val)
                ws.cell(row, idx + 1).value = val
            row += 1


@timer(tracer=False)
def time_limit_items(script_excel_path, objects_config_excel_obj, shopconfig_config_excel_obj):
    script_excel_obj = TimeLimitItems(script_excel_path)
    item_list = script_excel_obj.parse_items()
    result_dict = defaultdict(list)
    temp_objects_timelimit_item_list = list()
    temp_objects_timelimit_item_linkid = str()

    for item in item_list:
        item_type = item[0]
        item_type_id = item[1]
        item_name = item[2]
        item_time_limit = item[3]
        item_commentary = '{0}-{1}'.format(item_type, item_name)
        time_limit_seconds = str(int(item_time_limit) * 24 * 60 * 60)

        # 在ShopConfig表和objects表中查到永久道具，并获得其ID
        shopconfig_permanent_item = shopconfig_config_excel_obj.sr_specific_result(
            xpath='>>Config/BallEquipment/item', Commentary=item_name, EquipType=item_type_id, UseTime='0', IsVisiable='1')
        if shopconfig_permanent_item:
            permanent_item_id = str(shopconfig_permanent_item['Id'])
        else:
            logger.error('[{0}]没有搜到在ShopConfig.xlsx中的永久道具，请检查'.format(item_commentary))
            return None
        objects_permanent_item = objects_config_excel_obj.sr_specific_result(xpath='>>objects/item', id=permanent_item_id)
        if not objects_permanent_item:
            logger.error('[{0}]objects.xlsx中的永久道具，请检查'.format(item_commentary))
            return None

        # 在objects表中查找是否存在已配过的时效道具
        objects_timelimit_item = objects_config_excel_obj.sr_specific_result(
            xpath='>>objects/item', sheet_name='时效道具', linkid=permanent_item_id, validtime=time_limit_seconds, type='27')
        if objects_timelimit_item is not None and 'show' in objects_timelimit_item and objects_timelimit_item['show'] != '0':
            objects_timelimit_item = None

        # 找到已配过的时效道具，返回该道具ID
        if objects_timelimit_item:
            existed_timelimit_item_id = objects_timelimit_item['id']
            result_dict['RetID'].append(existed_timelimit_item_id)

        # 没找到则在ScriptExcel中生成新的时效道具
        else:
            objects_timelimit_item_list = objects_config_excel_obj.sr_specific_result(
                xpath='>>objects/item', sheet_name='时效道具', linkid=permanent_item_id, type='27', choose_result='All')

            # 由于每次查询时效道具都是从配置表中查询而新增的时效道具没有写入配置表，所以对于要生成多个时效道具时，
            # 需要将新生成的时效道具加入配置表中查询出的结果列表，从而让新生成时效道具的id不会重复。
            # 如果linkid不一致，则说明是不一样的永久道具，所以之前的查询结果也无效了，所以需要根据linkid多一层判断。
            if temp_objects_timelimit_item_linkid == permanent_item_id:
                if len(temp_objects_timelimit_item_list) > len(objects_timelimit_item_list):
                    objects_timelimit_item_list = temp_objects_timelimit_item_list

            # 找到了同一永久道具的其他时效道具，根据其id生成新id
            if objects_timelimit_item_list:
                # 生成新id
                new_timelimit_item_id = max(map(lambda d: int(d['id']), objects_timelimit_item_list))
                if str(item_type_id) == '11':
                    # 如果是关键词皮肤
                    new_timelimit_item_id = str((int(int(new_timelimit_item_id) / 10) + 1) * 10 + 3)
                else:
                    # 如果不是关键词皮肤
                    new_timelimit_item_id = str(int(new_timelimit_item_id) + 1)
            # 没找到同一永久道具的其他时效道具，根据永久道具id生成新id
            else:
                if str(item_type_id) == '11':
                    # 如果是关键词皮肤
                    new_timelimit_item_id = str(27000000 + (int((int(permanent_item_id) - 100000) / 10) * 10 + 1) * 10 + 3)
                else:
                    # 如果不是关键词皮肤
                    new_timelimit_item_id = '27' + str(permanent_item_id) + '1'

            # 根据永久道具生成其他属性，拼凑成shopconfig字典
            shopconfig_xpath = '>>Config/BallEquipment/item'
            shopconfig_id = new_timelimit_item_id
            shopconfig_commentary = '{0}({1}天)'.format(item_name, item_time_limit)
            shopconfig_equiptype = shopconfig_permanent_item['EquipType'] if 'EquipType' in shopconfig_permanent_item else None
            shopconfig_name = shopconfig_commentary
            shopconfig_icon = shopconfig_permanent_item['Icon'] if 'Icon' in shopconfig_permanent_item else None
            shopconfig_bundle = shopconfig_permanent_item['Bundle'] if 'Bundle' in shopconfig_permanent_item else None
            shopconfig_haveparticle = shopconfig_permanent_item['HaveParticle'] if 'HaveParticle' in shopconfig_permanent_item else None
            shopconfig_quality = shopconfig_permanent_item['Quality'] if 'Quality' in shopconfig_permanent_item else None
            shopconfig_isvisible = '0'
            shopconfig_usetime = time_limit_seconds
            shopconfig_animation = shopconfig_permanent_item['Animation'] if 'Animation' in shopconfig_permanent_item else None
            shopconfig_autocd = shopconfig_permanent_item['AutoCD'] if 'AutoCD' in shopconfig_permanent_item else None
            shopconfig_hide = '1'

            shopconfig_new_timelimit_item_dict = dict()
            shopconfig_new_timelimit_item_dict['>>XPath'] = shopconfig_xpath
            shopconfig_new_timelimit_item_dict['Id'] = shopconfig_id
            shopconfig_new_timelimit_item_dict['Commentary'] = shopconfig_commentary
            shopconfig_new_timelimit_item_dict['EquipType'] = shopconfig_equiptype
            shopconfig_new_timelimit_item_dict['Name'] = shopconfig_name
            shopconfig_new_timelimit_item_dict['Icon'] = shopconfig_icon
            shopconfig_new_timelimit_item_dict['Bundle'] = shopconfig_bundle
            shopconfig_new_timelimit_item_dict['HaveParticle'] = shopconfig_haveparticle
            shopconfig_new_timelimit_item_dict['Quality'] = shopconfig_quality
            shopconfig_new_timelimit_item_dict['IsVisiable'] = shopconfig_isvisible
            shopconfig_new_timelimit_item_dict['UseTime'] = shopconfig_usetime
            shopconfig_new_timelimit_item_dict['Animation'] = shopconfig_animation
            shopconfig_new_timelimit_item_dict['AutoCD'] = shopconfig_autocd
            shopconfig_new_timelimit_item_dict['Hide'] = shopconfig_hide

            result_dict['RetID'].append(shopconfig_id)
            result_dict['RetShopConfig'].append(shopconfig_new_timelimit_item_dict)

            # 根据永久道具生成其他属性，拼凑成objects字典
            objects_xpath = '>>objects/item'
            objects_id = new_timelimit_item_id
            objects_type = '27'
            objects_zprice = objects_permanent_item['zprice'] if 'zprice' in objects_permanent_item else None
            objects_validtime = time_limit_seconds
            objects_commentary = shopconfig_commentary
            objects_linkid = objects_permanent_item['id']

            objects_new_timelimit_item_dict = dict()
            objects_new_timelimit_item_dict['>>XPath'] = objects_xpath
            objects_new_timelimit_item_dict['id'] = objects_id
            objects_new_timelimit_item_dict['type'] = objects_type
            objects_new_timelimit_item_dict['zprice'] = objects_zprice
            objects_new_timelimit_item_dict['validtime'] = objects_validtime
            objects_new_timelimit_item_dict['Commentary'] = objects_commentary
            objects_new_timelimit_item_dict['linkid'] = objects_linkid

            temp_objects_timelimit_item_linkid = permanent_item_id
            temp_objects_timelimit_item_list = objects_timelimit_item_list
            if temp_objects_timelimit_item_list:
                temp_objects_timelimit_item_list.append(objects_new_timelimit_item_dict)
            else:
                temp_objects_timelimit_item_list = [objects_new_timelimit_item_dict]
            result_dict['RetObjects'].append(objects_new_timelimit_item_dict)

    # 将结果写入 ScriptExcel 表格
    retid_result_list = result_dict['RetID']
    retshopconfig_result_list = result_dict['RetShopConfig']
    retobjects_result_list = result_dict['RetObjects']

    script_excel_obj.write_item_id(retid_result_list)
    script_excel_obj.write_shopconfig(retshopconfig_result_list)
    script_excel_obj.write_objects(retobjects_result_list)
    script_excel_obj.save_workbook()
    logger.info('[{0}]新增时效道具已查询写入完毕'.format(script_excel_obj.file_path))
    return result_dict


if __name__ == '__main__':
    from Src.ConfigExcelParser import ConfigExcelParser
    objects_config_excel_path = os.path.join(CONFIG_EXCEL_DIR, 'objects.xlsx')
    shopconfig_config_excel_path = os.path.join(CONFIG_EXCEL_DIR, 'ShopConfig.xlsx')
    script_excel_path = os.path.join(SCRIPT_EXCEL_DIR, '时效道具.xlsx')

    objects_config_excel_obj = ConfigExcelParser(objects_config_excel_path)
    shopconfig_config_excel_obj = ConfigExcelParser(shopconfig_config_excel_path)

    time_limit_items(script_excel_path, objects_config_excel_obj, shopconfig_config_excel_obj)
